package com.zhj.agent.interceptor.resttemplate.sync;

import com.zhj.agent.common.ConstName;
import com.zhj.agent.core.RuntimeContextManager;
import com.zhj.agent.support.InstanceMethodsAroundInterceptor;

import org.springframework.http.client.AbstractClientHttpRequest;
import org.springframework.http.client.ClientHttpRequest;

import java.lang.reflect.Method;


/**
 * 请求拦截增强类
 */
public class RestRequestInterceptor implements InstanceMethodsAroundInterceptor {

    @Override
    public void beforeMethod(Object objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes) throws Throwable {

    }

    @Override
    public Object afterMethod(Object objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, Object result) throws Throwable {
        ClientHttpRequest clientHttpRequest = (ClientHttpRequest) result;
        if (clientHttpRequest instanceof AbstractClientHttpRequest) {
            AbstractClientHttpRequest httpRequest = (AbstractClientHttpRequest) clientHttpRequest;
            RuntimeContextManager.CarrierItem item = RuntimeContextManager.get();
            while (item.hasNext()) {
                item = item.next();
                httpRequest.getHeaders().add(ConstName.HEAD_KEY, item.getHeadValue());
            }
        }
        return result;
    }

    @Override
    public void handleMethodException(Object objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
        RuntimeContextManager.printTraceLog();
    }
}
